package org.ovirt.microvirt.services.events.impl;

import java.util.List;
import java.util.Map;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.ovirt.microvirt.beans.events.Event;
import org.ovirt.microvirt.services.events.BeansLookup;
import org.ovirt.microvirt.services.events.EventProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventProcessorImpl implements EventProcessor {

	final KnowledgeBase knowledgeBase;
	final BeansLookup lookup;
	private final static Logger logger = LoggerFactory
			.getLogger(EventProcessorImpl.class);

	public EventProcessorImpl(final BeansLookup lookup,
			final List<String> knowledgeResources) {
		final KnowledgeBuilder builder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();
		for (final String kresource : knowledgeResources) {
			builder.add(ResourceFactory.newClassPathResource(kresource),
					ResourceType.DRL);
			if (builder.hasErrors()) {
				for (final KnowledgeBuilderError error : builder.getErrors()) {
					logger.error(kresource + " " + error.getSeverity() + " "
							+ error.getMessage());
					throw new IllegalArgumentException(error.getMessage());
				}
			}
		}
		knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
		knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());
		this.lookup = lookup;
	}

	@Override
	public void process(final Event event) {
		StatefulKnowledgeSession session = knowledgeBase
				.newStatefulKnowledgeSession();
		for (final Map.Entry<String, Object> entry : lookup.lookupAll()
				.entrySet()) {
			session.getGlobals().set(entry.getKey(), entry.getValue());
		}
		session.getGlobals().set("logger", logger);
		session.insert(event);
		session.fireAllRules();
	}

}
